﻿namespace SampleApplication.ViewModels
{
    using System;
    using System.ComponentModel.DataAnnotations;
    using Microsoft.Practices.Prism.Interactivity.InteractionRequest;
    using Okazuki.MVVM.PrismSupport.Interactivity;
    using Okazuki.MVVM.PrismSupport.Utils;
    using Okazuki.MVVM.PrismSupport.ViewModels;
    using SampleApplication.Models;
    using Microsoft.Practices.Prism.Commands;

    public partial class PersonViewModel : ValidatableViewModelBase
    {
        public Person Model { get; private set; }

        [Required(ErrorMessage = "名前を入力してください")]
        public string Name { get; set; }

        [Required(ErrorMessage = "生年月日を入力してください")]
        public DateTime? Birthday { get; set; }

        [AutoInit]
        public InteractionRequest<DialogCloseNotification> WindowCloseRequest { get; private set; }

        [AutoInitCommand]
        public DelegateCommand CommitCommand { get; private set; }

        [AutoInitCommand]
        public DelegateCommand CancelCommand { get; private set; }

        public PersonViewModel(Person model)
        {
            if (model == null)
            {
                throw new ArgumentNullException("model");
            }

            this.Model = model;
            this.ApplyModelValue();
            this.ValidateProperties();
        }

        public void ApplyModelValue()
        {
            ObjectUtils.CopyTo(this.Model, this);
        }

        [CommandMethod(Name = "CommitCommand")]
        private void CommitExecute()
        {
            ObjectUtils.CopyTo(this, this.Model);
            this.WindowCloseRequest.Raise(
                new DialogCloseNotification(true));
        }

        [CommandMethod(Name = "CommitCommand")]
        private bool CanCommitExecute()
        {
            return !this.HasErrors;
        }

        [CommandMethod(Name = "CancelCommand")]
        private void CancelExecute()
        {
            this.WindowCloseRequest.Raise(
                new DialogCloseNotification(false));
        }
    }
}
